package com.newy.web.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.newy.core.AppException;
import com.newy.core.BaseController;
import com.newy.core.util.Converter;
import com.newy.core.util.Page;
import com.newy.core.web.AppContext;
import com.newy.domain.sys.Department;
import com.newy.domain.sys.Menu;
import com.newy.domain.sys.User;
import com.newy.domain.sys.vo.CurrentLoginInfo;
import com.newy.service.sys.DepartService;
import com.newy.service.sys.MenuService;
import com.newy.service.sys.UserService;


/**
 * 用户管理控制器类
 * @author linzongxue
 *
 */
@Controller
@RequestMapping("sys/user")
public class UserController extends  BaseController{
	@Resource private UserService userSvc;
	@Resource private DepartService departSvc;
	@Resource private MenuService menuSvc;
	
	/**
	 * 用户登陆，登陆成功返回登陆信息，登陆失败抛出错误。
	 */
	@RequestMapping("login") @ResponseBody
	public Map<String, Object> login(String code, String password){
		User loginUser = userSvc.login(code, password);
		if (loginUser == null){
			throw new AppException("登陆失败：用户名或密码错误");
		}
		return getLoginInfo();
	}

	/**
	 * 获取用户的登陆信息，如果用户未登陆返回null。登陆信息包括：
	 * <lu>
	 * <li>user： 登陆的用户对象
	 * <li>depart: 登陆用户所属的机构
	 * <li>menus: 用户关联的菜单({id:xx, name:xx});
	 * <li>sessionId: 会话ID
	 * </lu>
	 */
	@RequestMapping("getLoginInfo") @ResponseBody
	public Map<String, Object> getLoginInfo(){
		 Map<String, Object> loginInfo = new HashMap<String, Object>();
		 User user = AppContext.getLoginUser();
		 if (user == null) return null;
		 
		 loginInfo.put("user", user);
		 if (user.getDepartId() != null){
			 loginInfo.put("depart", departSvc.getDepart(user.getDepartId()));
		 }
		 loginInfo.put("menus", this.getAllMenusOfUser(user));
		 loginInfo.put("sessionId", AppContext.getRequest().getRequestedSessionId());
		 return loginInfo;
	}

	/**
	 * 用户退出登陆
	 */
	@RequestMapping("logout")
	public @ResponseBody void logout(){
		userSvc.logout();
	}

	@RequestMapping("save")
	public @ResponseBody User save(User user){
		userSvc.saveUser(user);
		return user;
	}

	@RequestMapping("get")
	public @ResponseBody User get(Long id){
		User user = userSvc.getUser(id);
		return user;
	}
	
	@RequestMapping("changePassword")
	public @ResponseBody void changePassword(String oldPwd, String newPwd){
		userSvc.changePassword(AppContext.getLoginUser(), oldPwd, newPwd);
	}
	
	@RequestMapping("delete")
	public @ResponseBody void delete(Long[] ids){
		userSvc.deleteUsers(ids);
	}
	
	/**
	 * 查询用户
	 */
	@RequestMapping("query")
	public @ResponseBody Page query(Page page, User user){
		userSvc.findUsersByPage(page, user);
		return new Converter()
			.addField("departName", "departId", Department.class, "name")
			.toListOfMap(page);
	}
	

	@RequestMapping("getRolesOfUser") @ResponseBody
	public Object getRolesOfUser(Long userId){
		return userSvc.getRolesOfUser(userId);
	}
	
	@RequestMapping("getUnselectedRolesOfUser") @ResponseBody
	public Object getUnselectedRolesOfUser(Long userId){
		return userSvc.getUnselectedRolesOfUser(userId);
	}
	
	@RequestMapping("addRolesToUser") @ResponseBody
	public void addRolesToUser(Long userId, Long[] roleIds){
		userSvc.addRolesToUser(userId, roleIds);
	}
	
	@RequestMapping("removeRolesFromUser") @ResponseBody
	public void removeRolesFromUser(Long userId, Long[] roleIds){
		userSvc.removeRolesFromUser(userId, roleIds);
	}

	/**
	 * 获取所有当前登陆信息
	 */
	@RequestMapping("getCurrentLoginInfoList")
	public @ResponseBody List<Map<String, Object>> getCurrentLoginInfoList(){
		List<CurrentLoginInfo> list = userSvc.getCurrentLoginInfoList();
		//必须移除session后再返回给页面
		return new Converter().removeField("session").toListOfMap(list);
	}
	
	/**
	 * 杀死会话（踢除登陆用户）
	 */
	@RequestMapping("killSession")
	public @ResponseBody void killSession(String sessionId){
		userSvc.killSession(sessionId);
	}
	
	/**
	 * 获取与用户关联的所有菜单，用于权限判断。
	 * 返回列表包括了所有目录、菜单项和按钮的id和name。
	 * @return Map列表，元素结构为：{id:xx, name:xx}
	 */
	private List<Map<String, Object>> getAllMenusOfUser(User user){
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		//遍历菜单，获取id和name
		for(Menu menu : menuSvc.getMenusOfUser(user)){
			Map<String, Object> item = new HashMap<String, Object>(2);
			item.put("id", menu.getId());
			String name = menu.getName();
			if (menu.isButton()){
				//补齐按钮名称
				name = menuSvc.getMenu(menu.getParentId()).getName() + "." + name;
			}
			item.put("name", name);
			result.add(item);
		}
		return result;
	}
}
